package com.qf.interceptor;

import com.qf.pojo.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AdminLoginInterceptor implements HandlerInterceptor {

    //预处理方法，返回值为true时继续向下执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("----------------开始--------------");
        //判断路径
        String url = request.getRequestURL().toString();
        System.out.println(url);
        //截取路径
        url = url.substring(url.lastIndexOf("/") );
//        System.out.println(url);
        //判断
        if ("/adminLogin.html".equals(url) || "/login".equals(url)) {
            System.out.println("true1");
            return true;
        } else {
            //如果session中有admin，说明登录过了，继续放行
            HttpSession session = request.getSession(false);//写false是获取session对象
            //接着判断
            if (session == null) {
                System.out.println("session为空");
                //用户me登录，跳转至登录页面
                request.getRequestDispatcher("/adminLogin.html").forward(request,response);
                System.out.println("session为空");
            } else {
                //有session ，判断域对象的值
                Admin admin = (Admin)session.getAttribute("admin");

                //判断admin
                if (admin != null) {
                    System.out.println("true2");
                    return true;
                } else {
                    //为空，说明没有登录
                    request.getRequestDispatcher("/adminLogin.html").forward(request,response);
                }
            }
        }

        System.out.println("----------------结束--------------");
//        return false;
        throw new RuntimeException("登录异常");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
